from django.db.models import Count
from django.http import HttpResponseNotFound, HttpResponseBadRequest
from django.shortcuts import *
from django.views import *
from home.models import *
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger #导入django分页插件
class IndexView(View):
    def get(self, request):
        # 1、获取所有分类信息数据
        categories = ArticleCategory.objects.all()
        # 2、接受用户点击的分类id
        cat_id = request.GET.get('cat_id',1)
        # 3、根据分类id进行分类的查询
        try:
            category = ArticleCategory.objects.filter(id = cat_id).first()
        except ArticleCategory.DoesNotExist:
            return HttpResponseRedirect('此分类信息不存在')
        # 5、根据分类信息查询该分类下的所有文章数据
        articles = Article.objects.filter(category=category)
        # 4、获取分页参数
        page_index = request.GET.get('page_index',1) #页码
        page_size = request.GET.get('page_size',2) #页容量

        # 6、创建分页器
        pages = Paginator(articles,page_size) #对查询到的数据对象articles进行分页，设置超过指定页容量就分页
        try:
            list = pages.page(page_index) #获取当前页面的记录
        except PageNotAnInteger:
            list = pages.page(1) #如果用户输入的页面不是整数时，显示第1页的内容

        comments = Comment.objects.all().values('article_id').annotate(artic_id=Count('article_id')).order_by(
            '-artic_id')[:2]
        comm_li = []
        for co in comments:
            # 通过字典拿值条件查询找到博客数据
            comm = Article.objects.filter(id=co['article_id'])
            comm_li.append(comm)

        new_a = Article.objects.order_by('-create_time')[:1]
        context = {
            'categories':categories,
            'category':category,
            'articles':list,
            'cat_id':cat_id,
            'new_a':new_a,
            'comm_li':comm_li
        }
        resp = render(request, 'index.html',context=context)
        resp.set_cookie('cat_id',cat_id)
        return resp


class DetailView(View):
    def get(self,request):
        art_id = request.GET.get('artid')

        try:
            article = Article.objects.get(id=art_id)
        except Article.DoesNotExist:
            return render(request,"404.html")

        article.total_views += 1
        article.save()
        comm = Comment.objects.filter(article=article).order_by('-created_time')
        for i in comm:
            print(i.user.avatar)
        corrtags = Article.objects.filter(tags=article.tags).order_by('?')[:3]
        # comments = Comment.objects.all().order_by('-artic_id')[:2]
        comm_li = []
        # print(comments)
        # for co in comments:
            # 通过字典拿值条件查询找到博客数据
            # comm = Article.objects.filter(id=co['article_id'])
            # comm_li.append(comm)
        context = {
            "article":article,
            'comms':comm,
            'corrtags':corrtags,
            'comm_li':comm_li
        }
        return render(request,'details.html',context=context)

    def post(self,request):
        user = request.user

        if user and user.is_authenticated:
            art_id = request.POST.get('art_id')
            content = request.POST.get('content')

            try:
                art = Article.objects.get(id=art_id)
            except Article.DoesNotExist:
                return HttpResponseBadRequest('该文章不存在')

            Comment.objects.create(content=content,article=art,user=user)

            art.comments_count += 1
            art.save()

            req_url = request.path + '?artid=' +art_id
            return redirect(req_url)
        else:
            return redirect(reverse('users:login'))
